import asyncio
from playwright.async_api import async_playwright

async def automate_paipan():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        page = await browser.new_page()
        
        # 打开八字排盘网站
        await page.goto('https://pcbz.iwzwh.com/#/paipan/index')
        
        # 填写姓名
        name_input = await page.query_selector('div.el-input input')
        if name_input:
            await name_input.fill('李四')
        
        # 选择性别（男）
        await page.click('.form-row-item-sex:nth-child(1) > img')
        
        # 点击日期输入框
        date_input = await page.query_selector('.input-box:nth-child(3) > .bogus-input')
        if date_input:
            await date_input.click()
            
            # 输入日期和时间
            date_dialog_input = await page.query_selector('input.datetime_search_input')
            if date_dialog_input:
                await date_dialog_input.fill('201001101000')
                
                fill_confirm_button = await page.query_selector('.datetime_search_btn')
                if fill_confirm_button:
                    await fill_confirm_button.click()
                # 点击确认按钮
                    confirm_button = await page.query_selector('span.datetime_confirm')
                    if confirm_button:
                        await confirm_button.click()

        # 选择出生地
        location_input = await page.query_selector('.input-box:nth-child(4) > .bogus-input')
        if location_input:
            await location_input.click()
            # location_dialog_input = await page.query_selector("input[placeholder='搜索全国城市及地区']")
            # if location_dialog_input:
            #     await location_dialog_input.fill('天津')
            #     first_location = await page.query_selector("div[class='datetime_search_popover'] div:nth-child(1)") 
            #     if first_location:
            #         await first_location.click()
            location_item = await page.query_selector("//div[contains(text(),'天津')]")
            if location_item:
                await location_item.click()
                
                # 点击提交按钮
                confirm_button = await page.query_selector("div[id='datetime_box'] span[class='datetime_confirm']")
                if confirm_button:
                    await confirm_button.click()
        # 保持浏览器打开以便查看结果
        input("按Enter键关闭浏览器...")
        await browser.close()

# 运行自动化脚本
asyncio.run(automate_paipan())